package com.atguigu.gmall.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;


    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 渲染首页
     * @param model
     * @return
     */
    @GetMapping({"/", "/index.html"})
    public String index(Model model) {
        //1.远程获取分类数据
        List<JSONObject> list = productFeignClient.getBaseCategoryList();

        //2.添加数据到模型对象Model
        model.addAttribute("list", list);

        //3.返回模板页面
        return "/index/index.html";
    }





    /**
     * 基于模板技术生成首页的html文件
     * @return
     */
    @GetMapping("/createIndex")
    @ResponseBody
    public Result createIndexHtmlDoc(){
        try {
            //1.声明模板
            String template = "/index/index.html";

            //2.创建上下文对象-作用封装模板需要数据模型
            List<JSONObject> list = productFeignClient.getBaseCategoryList();
            Context context = new Context();
            context.setVariable("list", list);


            //3.通过模板引擎将数据跟模板页面合并 生成文件到指定目录({nginx_home}/html目录)
            FileWriter fileWriter = new FileWriter("d:\\index.html");
            templateEngine.process(template, context, fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

}
